package com.greenantmall.utils;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.greenantmall.AntHomeApplication;
import com.greenantmall.R;
import com.greenantmall.activity.LoginActivity;
import com.greenantmall.bean.Goods;
import com.greenantmall.bean.MyMsg;
import com.greenantmall.bean.Order;
import com.greenantmall.bean.OrderItem;
import com.greenantmall.bean.OrderStatusCode;
import com.greenantmall.bean.ServerSection;
import com.greenantmall.bean.ShoppingCart;
import com.greenantmall.bean.StoreInfo;
import com.greenantmall.bean.UIGoods;
import com.greenantmall.service.RetrieveDataAsyn;
import com.greenantmall.service.RetrieveDataListener;
import com.greenantmall.view.ChoosePayMethodDialog;
import com.greenantmall.view.CommonDialog;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UtilTools
{
    public static void showMyToast(Context context, String text)
    {
        if (context == null)
        {
            return;
        }

        try
        {
            // content view
            View contentView = LayoutInflater.from(context).inflate(R.layout.toast, null);
            TextView tv = (TextView) contentView.findViewById(R.id.toast_text);
            tv.setText((text == null ? "" : text));

            // show toast
            Toast toast = new Toast(context);
            toast.setView(contentView);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.show();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    
    public static void exit(Context context){
      ImageLoader.getInstance().clearMemoryCache();
      AppExitManager.getInstance().appExit(context);  
    }
    
    public static ServerSection getServerSection(Application application) {
    	String spName = "sp_name_server_section";
    	String spKeySelectCity = "sp_key_select_city";
        String spKeySelectArea = "sp_key_select_area";
        String spKeySelectUpTown = "sp_key_select_uptown";
        String spKeyPickupStation = "sp_key_pickup_station";
        String spKeyObjectId = "sp_key_object_id";
        String spKeySelectSectionNum = "sp_key_select_section_num";
        String spKeyShowOpenTime = "sp_key_open_time";
        String spKeyShowCloseTime = "sp_key_close_time";
        String spKeyNotice = "sp_key_notice";
        String spKeyCvsid = "sp_key_cvsid";
        
        ServerSection serverSection = new ServerSection();
        SharedPreferences sp = application.getSharedPreferences(spName, Application.MODE_PRIVATE);
        serverSection.setCity(sp.getString(spKeySelectCity, ""));
        serverSection.setArea(sp.getString(spKeySelectArea, ""));
        serverSection.setUptown(sp.getString(spKeySelectUpTown, ""));
        serverSection.setPickupStation(sp.getString(spKeyPickupStation, ""));
        serverSection.setObjectId(sp.getString(spKeyObjectId, ""));
        serverSection.setSectionnum(sp.getInt(spKeySelectSectionNum, -1));
        serverSection.setOpenTimeStr(sp.getString(spKeyShowOpenTime, ""));
        serverSection.setCloseTimeStr(sp.getString(spKeyShowCloseTime, ""));
        serverSection.setNotice(sp.getString(spKeyNotice, ""));
        serverSection.setCvsid(sp.getString(spKeyCvsid, ""));
	    return serverSection;
    }
    
    public static void saveServerSection(Application application, ServerSection serverSection) {
    	String spName = "sp_name_server_section";
    	String spKeySelectCity = "sp_key_select_city";
        String spKeySelectArea = "sp_key_select_area";
        String spKeySelectUpTown = "sp_key_select_uptown";
        String spKeyPickupStation = "sp_key_pickup_station";
        String spKeyObjectId = "sp_key_object_id";
        String spKeySelectSectionNum = "sp_key_select_section_num";
        String spKeyShowOpenTime = "sp_key_open_time";
        String spKeyShowCloseTime = "sp_key_close_time";
        String spKeyNotice = "sp_key_notice";
        String spKeyCvsid = "sp_key_cvsid";
        
        SharedPreferences sp = application.getSharedPreferences(spName, Application.MODE_PRIVATE);
        Editor editor = sp.edit();
        editor.putString(spKeySelectCity, serverSection.getCity());
        editor.putString(spKeySelectArea, serverSection.getArea());
        editor.putString(spKeySelectUpTown, serverSection.getUptown());
        editor.putString(spKeyPickupStation, serverSection.getPickupStation());
        editor.putString(spKeyObjectId, serverSection.getObjectId());
        editor.putInt(spKeySelectSectionNum, serverSection.getSectionnum());
        editor.putString(spKeyShowOpenTime, serverSection.getOpenTimeStr());
        editor.putString(spKeyShowCloseTime, serverSection.getCloseTimeStr());
        editor.putString(spKeyNotice, serverSection.getNotice());
        editor.putString(spKeyCvsid, serverSection.getCvsid());
	    editor.commit();
	    
	    AntHomeApplication.sectionNum = serverSection.getSectionnum();
    }
    
    public static ArrayList<String> getSearchHistory(Application application) {
    	String spName = "sp_name_search_history";
    	String spKeySearchHistory = "sp_key_search_history";
        
        SharedPreferences sp = application.getSharedPreferences(spName, Application.MODE_PRIVATE);
        Set<String> historySet = sp.getStringSet(spKeySearchHistory, null);
        
        ArrayList<String> tempHistoryList = new ArrayList<String>();
        if(historySet != null) {
        	for(String historyStr : historySet) {
            	tempHistoryList.add(historyStr);
            }
        }
        
        Collections.sort(tempHistoryList, new Comparator<String>() {
			@Override
			public int compare(String lhs, String rhs) {
				int l = Integer.valueOf(lhs.substring(0, 1));
				int r = Integer.valueOf(rhs.substring(0, 1));
				return l - r;
			}
		});
        
        ArrayList<String> historyList = new ArrayList<String>();
        for(String str : tempHistoryList) {
        	historyList.add(str.substring(1));
        }
	    return historyList;
    }
    
    public static void saveSearchHistory(Application application, String historyStr) {
    	Set<String> historySet = new TreeSet<String>();
    	List<String> list = getSearchHistory(application);
    	if(list != null && list.size() > 0) {
    		list.remove(historyStr);
    		list.add(historyStr);
    		int size = list.size();
    		for(int i=size-1; i>=0; i--) {
    			historySet.add(i + list.get(i));
    			if(historySet.size() >= 10) {
    				break;
    			}
    		}
    	}
    	else {
    		historySet.add(0 + historyStr);
    	}
    	
    	String spName = "sp_name_search_history";
    	String spKeySearchHistory = "sp_key_search_history";
    	
        SharedPreferences sp = application.getSharedPreferences(spName, Application.MODE_PRIVATE);
        Editor editor = sp.edit();
        editor.putStringSet(spKeySearchHistory, historySet);
	    editor.commit();
    }
    
    public static void clearSearchHistory(Application application) {
    	String spName = "sp_name_search_history";
    	String spKeySearchHistory = "sp_key_search_history";
    	
    	SharedPreferences sp = application.getSharedPreferences(spName, Application.MODE_PRIVATE);
        Editor editor = sp.edit();
        editor.remove(spKeySearchHistory);
	    editor.commit();
    }
    
    public static boolean isUserLogined(Context context){
        AVUser currentUser = AVUser.getCurrentUser();
        if (currentUser != null)
        {
            return true;  
        }else{
            Intent intent = new Intent(context, LoginActivity.class);
            context.startActivity(intent);  
            return false;  
        }
    }
    public static void cleanAllCache(Context context)
    {

        String packageName = context.getPackageName();
        FileUtils.reverseDeleteFile(context.getCacheDir());
        FileUtils.reverseDeleteFile(ImageLoader.getInstance().getDiskCache().getDirectory());
        
    }
    public static void processUserChangeShoppingCart(final Context context){
    	AntHomeApplication.shoppingMap.clear();
    	if (AVUser.getCurrentUser() != null) {
			// TODO 获取购物车
			RetrieveDataAsyn.getInstance().getShoppingCart(
					AVUser.getCurrentUser().getObjectId(), AntHomeApplication.sectionNum, 0,
					new RetrieveDataListener() {

						@Override
						public void dataRetrieved(int requestId, Object data) {
							List<ShoppingCart> datas = (List<ShoppingCart>) data;
							if (datas != null) {
								for (int i = 0; i < datas.size(); i++) {
									AntHomeApplication.shoppingMap.put(datas.get(i).getGoodsid(),
											datas.get(i));
								}
								Intent intent = new Intent(
										Const.SHOPPING_CART_CHANGED);
								context.sendBroadcast(intent);
							}
						}
					});
		}
    }
    
    /**
     * 通过商品或者购物车判断是否是SP商店
     * @param goods
     * @param shoppingCart
     * @return
     */
    public static boolean isSPStore(Goods goods,ShoppingCart shoppingCart){
    	if(goods==null&&shoppingCart!=null)
    	{
    		String storeId = shoppingCart.getStoreId();
    		if(TextUtils.isEmpty(storeId))
    		{
    			Goods tempGoods=shoppingCart.getGoods();
    			if(tempGoods!=null)
        		{
    				storeId=tempGoods.getStoreId();	
        		}
    			
    		}else{
    			
    		}
    		StoreInfo tempStore = AntHomeApplication.storeInfos.get(storeId);
			if(tempStore!=null&&StoreInfo.STORE_TYPE_SP.equals(tempStore.getStoreStyle()))
			{
				return true;
			}
    		
    		
    	}else if(goods!=null&&shoppingCart==null){
    		StoreInfo tempStore = AntHomeApplication.storeInfos.get(goods.getStoreId());
			if(tempStore!=null&&StoreInfo.STORE_TYPE_SP.equals(tempStore.getStoreStyle()))
			{
				return true;
			}
    	}else if(goods!=null&&shoppingCart!=null)
    	{
    		StoreInfo tempStore = AntHomeApplication.storeInfos.get(goods.getStoreId());
			if(tempStore!=null&&StoreInfo.STORE_TYPE_SP.equals(tempStore.getStoreStyle()))
			{
				return true;
			}
    	}else{
    		
    	}
    	
    	return false;
    }
    
    /**
     * 购物车数据
     */
	public static List<ShoppingCart> getShoppingCartDatas() {
		List<ShoppingCart> shoppingCarts = new ArrayList<ShoppingCart>();
		Iterator<Entry<String, ShoppingCart>> iter = AntHomeApplication.shoppingMap
				.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry<String, ShoppingCart> entry = (Map.Entry<String, ShoppingCart>) iter
					.next();
			Object key = entry.getKey();
			ShoppingCart val = entry.getValue();
			shoppingCarts.add(val);
		}
		return shoppingCarts;
	}
    
    /**
     * sp商品
     * @return
     */
	public static List<ShoppingCart> getSpShoppingCartItems() {
		List<ShoppingCart> shoppingCarts = new ArrayList<ShoppingCart>();
		Iterator<Entry<String, ShoppingCart>> iter = AntHomeApplication.shoppingMap
				.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry<String, ShoppingCart> entry = (Map.Entry<String, ShoppingCart>) iter
					.next();
			Object key = entry.getKey();
			ShoppingCart val = entry.getValue();
			if(isSPStore(null,val))
			{
				shoppingCarts.add(val);
			}
		}
		return shoppingCarts;
	}
    /**
     * 独立商铺的购物车
     * @param storeId
     * @return
     */
	public static List<ShoppingCart> getNotSpShoppingCartItems(String storeId) {
		List<ShoppingCart> shoppingCarts = new ArrayList<ShoppingCart>();
		Iterator<Entry<String, ShoppingCart>> iter = AntHomeApplication.shoppingMap
				.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry<String, ShoppingCart> entry = (Map.Entry<String, ShoppingCart>) iter
					.next();
			Object key = entry.getKey();
			ShoppingCart val = entry.getValue();
			if (isSPStore(null, val)) {

			} else {
				// TODO 购物车区分独立商铺
				Goods goods=val.getGoods();
				if (!TextUtils.isEmpty(storeId)
						&& (storeId.equals(val.getStoreId())||(goods!=null&&storeId.equals(goods.getStoreId()))))
				{
					shoppingCarts.add(val);
				}
					
			}
		}
		return shoppingCarts;
	}
	/**
	 * 根据订单列表获取总支付金额
	 * @param items
	 * @return
	 * @since 3.8
	 */
    public static String getTotalCostByOrderItems(List<OrderItem> items)
    {
        DecimalFormat df = new DecimalFormat("#########.##");
        double totalCost = 0;
        if (items != null && items.size() > 0)
        {

            for (int i = 0; i < items.size(); i++)
            {
                OrderItem orderItem = items.get(i);
                if (orderItem.isWeighAble())
                {
                    if (orderItem.getWeight() < 0.000001)
                    {
                        totalCost = 0;
                        break;
                    } else
                    {
                        totalCost += (orderItem.getWeight() * orderItem.getPrice());
                    }
                } else
                {
                    totalCost += (orderItem.getQuantity() * orderItem.getPrice());
                }
            }
        }

        return df.format(totalCost);
    }

	/**
	 * 处理button和textview状态
	 * 
	 * @param statusCode
	 * @param statuss
	 * @param close
	 * @param payContinue
	 * @param order_detail_status
	 */

	public static void processOrderStatus(Button close, Button payContinue, TextView order_detail_status,
			Context context, Order order) {
		int statusCode = order.getStatusCode();
		String[] orderStatus = context.getResources().getStringArray(R.array.order_status_code);
		close.setVisibility(View.VISIBLE);
		payContinue.setVisibility(View.VISIBLE);

		try {
			order_detail_status.setText(orderStatus[statusCode]);
		} catch (Exception e) {
			e.printStackTrace();
		}

		switch (OrderStatusCode.values()[statusCode]) {
		case ORDER_PENDING:// 0 -待发货
			if (order.isPayed()) {
				payContinue.setVisibility(View.GONE);
				close.setText(R.string.button_order_return);
				order_detail_status.setText(R.string.order_status_code_1);
			} else {
				payContinue.setText(R.string.button_order_paycontinue);
				close.setText(R.string.button_order_cancel);
				order_detail_status.setText(R.string.order_status_code_0);
			}
			break;
		case ORDER_2_STATION:// 2-已送至自提点
			payContinue.setText(R.string.button_order_confirm);
			close.setVisibility(View.GONE);
			order_detail_status.setText(R.string.order_status_code_3);
			break;
		case ORDER_SHIPPED:// 1-已发货
		case ORDER_WAIT_FOR_SIGN:// 5-待收货
			payContinue.setText(R.string.button_order_confirm);
			close.setVisibility(View.GONE);
			order_detail_status.setText(R.string.order_status_code_2);
			break;
		case ORDER_SIGNED:// 3-已签收
			close.setText(R.string.button_order_return);
			payContinue.setText(R.string.button_order_close);
			order_detail_status.setText(R.string.order_status_code_4);
			break;
		case ORDER_WAIT_FOR_PAY:// 4-待付款
			payContinue.setText(R.string.button_order_paycontinue);
			close.setText(R.string.button_order_cancel);
			order_detail_status.setText(R.string.order_status_code_5);
			break;
		case ORDER_WEIGHED:// 9-已称重
			if (order.isPayed()) {
				close.setText(R.string.button_order_return);
				payContinue.setVisibility(View.GONE);
				order_detail_status.setText(R.string.order_status_code_7);
			} else {
				order_detail_status.setText(R.string.order_status_code_6);
				payContinue.setText(R.string.button_order_paycontinue);
				close.setText(R.string.button_order_cancel);
			}
			break;
		case ORDER_UN_WEIGHED:// 13-未称重
			payContinue.setVisibility(View.GONE);
			close.setText(R.string.button_order_cancel);
			order_detail_status.setText(R.string.order_status_code_8);
			break;
		default:
			close.setVisibility(View.GONE);
			payContinue.setVisibility(View.GONE);
			break;
		}

	}
	
	public static void processOrderButtonClick(final Button close, final Button payContinue,
			final TextView order_detail_status, final Context context, final Order order, final BaseAdapter adapter) {
		close.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				// 催促发货
				if (context.getString(R.string.button_order_hurry).equals(close.getText().toString())) {
					CommonDialog errDialog = new CommonDialog(context, R.style.ExitDialogStyle,
							context.getString(R.string.common_title),
							context.getString(R.string.button_order_hurry_hint));
					errDialog.setSureListener(new CommonDialog.OnSureClickListener() {

						@Override
						public void sureClicked() {

						}
					});
					errDialog.show();
				}
				// 申请退货
				else if (context.getString(R.string.button_order_return).equals(close.getText().toString())) {
					CommonDialog errDialog = new CommonDialog(context, R.style.ExitDialogStyle,
							context.getString(R.string.common_title),
							context.getString(R.string.button_order_return_hint));
					errDialog.setSureListener(new CommonDialog.OnSureClickListener() {

						@Override
						public void sureClicked() {

							RetrieveDataAsyn.getInstance().updateOrder(AVUser.getCurrentUser().getObjectId(),
									order.getOrderId(), OrderStatusCode.ORDER_REFUNDING.value(), 0,
									new RetrieveDataListener() {

								@Override
								public void dataRetrieved(int requestId, Object data) {
									if (data == null) {
										UtilTools.showMyToast(context, context.getString(R.string.failed));
									} else {
										UtilTools.showMyToast(context, context.getString(R.string.success));
										order.setStatusCode(OrderStatusCode.ORDER_REFUNDING.value());
										processOrderStatus(close, payContinue, order_detail_status, context, order);
										NotificationUtil.sendPrivateMsg(
												context.getString(R.string.order_msssage_return, order.getOrderId()),
												order.getOrderId(), MyMsg.MSG_TYPE_ORDERDETAIL);
										if (adapter != null)
											adapter.notifyDataSetChanged();
									}
								}
							});

						}
					});
					errDialog.show();
				}else if(context.getString(R.string.button_order_cancel).equals(close.getText().toString())){
					cancelOrder(close, payContinue,
							order_detail_status,context,  order, adapter);
				}
				
				

			}
		});

		payContinue.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				// 继续支付
				if (context.getString(R.string.button_order_paycontinue).equals(payContinue.getText().toString())) {
					AVObject av = new AVObject();
					Set<String> sets = order.keySet();
					Iterator<String> it = sets.iterator();
					while (it.hasNext()) {
						String str = it.next();
						av.put(str, order.get(str));
					}

					List<AVObject> orderList = new ArrayList<AVObject>();
					orderList.add(av);
					Activity activity = (Activity) context;
					ChoosePayMethodDialog choosePayMethodDialog = new ChoosePayMethodDialog(activity, orderList,
							new PayCompleteListener() {

						@Override
						public void payComplete() {
							refreshOrder( close, payContinue, order_detail_status,
									context, order, adapter);
						}

						@Override
						public void notChoosePayMethod() {
						}
					});
					choosePayMethodDialog.show();
					iLog.d("choosePayMethodDialog show");
				}
				// 取消订单
				else if (context.getString(R.string.button_order_cancel).equals(payContinue.getText().toString())) {
					
					cancelOrder(close, payContinue,
							order_detail_status,context,  order, adapter);
					
				} else if (context.getString(R.string.button_order_confirm).equals(payContinue.getText().toString())) {

					CommonDialog errDialog = new CommonDialog(context, R.style.ExitDialogStyle,
							context.getString(R.string.common_title),
							context.getString(R.string.button_order_confirm_hint));
					errDialog.setSureListener(new CommonDialog.OnSureClickListener() {

						@Override
						public void sureClicked() {
							RetrieveDataAsyn.getInstance().updateOrder(AVUser.getCurrentUser().getObjectId(),
									order.getOrderId(), OrderStatusCode.ORDER_SIGNED.value(), 0,
									new RetrieveDataListener() {

								@Override
								public void dataRetrieved(int requestId, Object data) {
									if (data == null) {
										UtilTools.showMyToast(context, context.getString(R.string.failed));
									} else {
										UtilTools.showMyToast(context, context.getString(R.string.success));
										order.setStatusCode(OrderStatusCode.ORDER_SIGNED.value());
										processOrderStatus(close, payContinue, order_detail_status, context, order);
										if (adapter != null)
											adapter.notifyDataSetChanged();
									}
								}
							});
						}
					});
					errDialog.show();

				}
				// 关闭订单
				else if (context.getString(R.string.button_order_close).equals(payContinue.getText().toString())) {
					CommonDialog errDialog = new CommonDialog(context, R.style.ExitDialogStyle,
							context.getString(R.string.common_title),
							context.getString(R.string.button_order_close_hint));
					errDialog.setSureListener(new CommonDialog.OnSureClickListener() {

						@Override
						public void sureClicked() {
							RetrieveDataAsyn.getInstance().updateOrder(AVUser.getCurrentUser().getObjectId(),
									order.getOrderId(), OrderStatusCode.ORDER_CLOSED.value(), 0,
									new RetrieveDataListener() {

								@Override
								public void dataRetrieved(int requestId, Object data) {
									if (data == null) {
										UtilTools.showMyToast(context, context.getString(R.string.failed));
									} else {
										UtilTools.showMyToast(context, context.getString(R.string.success));
										order.setStatusCode(OrderStatusCode.ORDER_CLOSED.value());
										processOrderStatus(close, payContinue, order_detail_status, context, order);
										NotificationUtil.sendPrivateMsg(
												context.getString(R.string.order_msssage_close, order.getOrderId()),
												order.getOrderId(), MyMsg.MSG_TYPE_ORDERDETAIL);
										if (adapter != null)
											adapter.notifyDataSetChanged();
									}
								}
							});
						}
					});
					errDialog.show();
				}

			}
		});

	}
	/**
	 * 取消订单
	 * @param close
	 * @param payContinue
	 * @param order_detail_status
	 * @param context
	 * @param order
	 * @param adapter
	 */
	private static void cancelOrder(final Button close, final Button payContinue,
			final TextView order_detail_status, final Context context, final Order order, final BaseAdapter adapter){

		CommonDialog errDialog = new CommonDialog(context, R.style.ExitDialogStyle,
				context.getString(R.string.common_title),
				context.getString(R.string.button_order_cancel_hint));
		errDialog.setSureListener(new CommonDialog.OnSureClickListener() {

			@Override
			public void sureClicked() {
				

				RetrieveDataAsyn.getInstance().updateOrder(AVUser.getCurrentUser().getObjectId(),
						order.getOrderId(), OrderStatusCode.ORDER_CANCELED.value(), 0,
						new RetrieveDataListener() {

					@Override
					public void dataRetrieved(int requestId, Object data) {
						if (data == null) {
							UtilTools.showMyToast(context, context.getString(R.string.failed));
						} else {
							if(order.getFavorableCost()>0.001)
							{
								AVUser user = AVUser.getCurrentUser();

								if (user != null) {
									// 是否已经使用过首单减免
//									boolean isused = user.getBoolean("firstOrderDiscountUsed");
									user.put("firstOrderDiscountUsed", false);
									user.saveInBackground();
								}
							}
							UtilTools.showMyToast(context, context.getString(R.string.success));
							order.setStatusCode(OrderStatusCode.ORDER_CANCELED.value());
							processOrderStatus(close, payContinue, order_detail_status, context, order);
							NotificationUtil.sendPrivateMsg(
									context.getString(R.string.order_msssage_cancel, order.getOrderId()),
									order.getOrderId(), MyMsg.MSG_TYPE_ORDERDETAIL);
							if (adapter != null)
								adapter.notifyDataSetChanged();
						}
					}
				});
			}
		});
		errDialog.show();
	
	}

	/**
	 * 支付完成之后刷新订单使用
	 * 
	 * @param close
	 * @param payContinue
	 * @param order_detail_status
	 * @param context
	 * @param order
	 * @param adapter
	 */
	private static void refreshOrder(final Button close, final Button payContinue, final TextView order_detail_status,
			final Context context, final Order order, final BaseAdapter adapter) {

		RetrieveDataAsyn.getInstance().getOrderDetail(order.getObjectId(), 0, new RetrieveDataListener() {

			@Override
			public void dataRetrieved(int requestId, Object data) {

				if (data != null) {
					Order tempOrder = (Order) data;

					order.put(Order.ATTR_ORDERITEMS, tempOrder.getString(Order.ATTR_ORDERITEMS));
					order.setStatusCode(tempOrder.getStatusCode());
					order.setAddress(tempOrder.getAddress());
					order.setOrderType(tempOrder.getOrderType());
					order.setPayWay(tempOrder.getPayWay());
					order.setDeliveryTime(tempOrder.getDeliveryTime());
					order.setDeliveryWay(tempOrder.getDeliveryWay());
					order.setPayTime(tempOrder.getPayTime());
					order.setTotalCost(tempOrder.getTotalCost());
					order.setDeliveryCost(tempOrder.getDeliveryCost());
					order.setPayed(tempOrder.isPayed());
					if (adapter != null) {
						adapter.notifyDataSetChanged();
					}
					processOrderStatus(close, payContinue, order_detail_status, context, order);

				}

			}
		});

	}
	
	public static boolean isEmail(String email) {
		String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(email);

		return m.matches();
	}
	
	public static Date parseDateStr(String formatStr, String dateStr) {
		SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
		try {
			Date date = sdf.parse(dateStr);
			Log.d("CEXX", "CEXX ---> parseDateStr ---> hour : " + date.getHours());
			Log.d("CEXX", "CEXX ---> parseDateStr ---> minute : " + date.getMinutes());
			return date;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return Calendar.getInstance().getTime();
	}
	
	public static Goods uiGoodsToGoods(UIGoods uiGoods) {
    	Goods goods = new Goods();
    	goods.setStoreId(uiGoods.getStoreId());
    	goods.setObjectId(uiGoods.getObjectId());
        goods.setDescription(uiGoods.getDescroption());
        goods.setSpecs(uiGoods.getSpecs());
        goods.setDiscount(uiGoods.getDiscount());
        goods.setImageUrl(uiGoods.getPicUrl());
        goods.setPrice(uiGoods.getPriceBeforeDiscount());
        goods.setShowTag(uiGoods.getShowTag());
        goods.setUnit(uiGoods.getUnit());
        goods.setWeighUnit(uiGoods.getStepUnit());
        goods.setWeighStep(uiGoods.getStep());
        goods.setWeighAble(uiGoods.isPriceByWeight());
        goods.setTotalSales(uiGoods.getBuyedPeopleCount());
        goods.setStock(uiGoods.getStock());
        return goods;
    }
}




